/* eslint-disable camelcase */

import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import { gql, useQuery, useMutation } from '@apollo/client';

import notification from '@kuiper-components/notification';
import Dialog from '@kuiper-components/dialog';
import Button from '@kuiper-components/button';

import Textarea from '../../../../../components/Textarea';
import s from './Edit.module.css';
import Label from '../../../../../components/Label';
import Loading from '@kuiper-components/loading';

const EDIT_GQL = gql`
	mutation($words: [String]!, $type: String, $formSerializer: any) {
		explictKeywordEdit(input: { words: $words, type: $type })
			@rest(
				type: "ExplictKeywordEditResponse"
				path: "/kb/custom_keywords"
				method: "POST"
				endpoint: "v2"
				bodySerializer: $formSerializer
			) {
			code
			msg
		}
	}
`;

const QUERY_GQL = gql`
	query($type: String!) {
		explictKeywordCategoryDetail(type: $type)
			@rest(
				type: "ExplictKeywordCategoryDetail"
				path: "/kb/keywords/{args.type}"
				endpoint: "v2"
			) {
			custom_keywords
			system_keywords
		}
	}
`;
const typeArr = [
	'',
	'政治',
	'涉黄',
	'反动',
	'涉黑',
	'暴恐',
	'博彩',
	'民生',
	'其他',
	'ChatGPT'
];
export default function Edit({ className, refetch, type, ...props }) {
	const [dialogVisible, setDialogVisible] = React.useState(false);
	const [text, setText] = React.useState('');
	const [warning, setWarning] = React.useState('');
	const { data, loading } = useQuery(QUERY_GQL, {
		skip: !dialogVisible || !type,
		fetchPolicy: 'cache-and-network',
		variables: { type },
	});

	const [edit] = useMutation(EDIT_GQL);

	const customKeywords =
		data?.explictKeywordCategoryDetail?.custom_keywords || [];
	const [prevCustomKeywords, setPrevCustomKeywords] = React.useState('');
	React.useMemo(() => {
		if (prevCustomKeywords === customKeywords.join(' ')) {
			return;
		}

		setPrevCustomKeywords(customKeywords.join(' '));
		setText(customKeywords.join(' '));
	}, [customKeywords.join(' ')]);

	const handleOpenDialog = () => {
		setDialogVisible(true);
	};
	const handleClose = () => {
		setText('');
		setWarning('');
		setDialogVisible(false);
		refetch && refetch();
	};
	const handleTextChange = e => {
		const text = e.target.value;
		setText(text);
		if (text.match(/\S{40}/)) {
			setWarning('单个词不允许超过40个字符');
		} else {
			setWarning('');
		}
	};
	const handleSubmit = () =>
		edit({
			variables: { type, words: text.trim().split(/\s+/).filter(Boolean) },
		})
			.then(() => {
				notification.success({
					message: `修改敏感词成功`,
					placement: 'top',
				});
				handleClose();
			})
			.catch(error =>
				notification.error({
					message: `修改敏感词失败`,
					description: error.message,
					placement: 'top',
				})
			);

	return (
		<>
			<Button
				link
				primary
				className={cn(className, s.btn)}
				onClick={handleOpenDialog}
			>
				修改
			</Button>
			<Dialog
				visible={dialogVisible}
				destroyOnClose={true}
				title={`${typeArr[type]}敏感词设置`}
				wrapClassName={s.dialog}
				{...props}
				onClose={handleClose}
				maskStyle={{ zIndex: 100 }}
			>
				<Loading hasData show={loading}>
					<div className={s.loadingContainer}>
						<Label>默认词库</Label>
						<Textarea
							disabled
							className={cn(s.textarea, s.defaultLibrary)}
							placeholder="默认词库"
							rows="5"
							value={data?.explictKeywordCategoryDetail?.system_keywords?.join(
								' '
							)}
						/>
						<Label>自定义词库</Label>
						<Textarea
							className={cn(s.textarea, { [s.hasWarning]: warning })}
							placeholder="请输入敏感词，按空格隔开，每个敏感词不超过40字符。"
							rows="5"
							value={text}
							onChange={handleTextChange}
						/>
						<div className={s.warning}>{warning}</div>
					</div>
				</Loading>
				<div className={s.actions}>
					<Button onClick={handleClose}>取消</Button>
					<Button primary onClick={handleSubmit}>
						确定
					</Button>
				</div>
			</Dialog>
		</>
	);
}

Edit.propTypes = {
	className: PropTypes.string,
	refetch: PropTypes.func,
	type: PropTypes.string,
};

Edit.defaultProps = {
	className: '',
	refetch: () => {},
};
